// pages/auction/index.js
const app = getApp();
const action = require('../../utils/action.js');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    currentTab: 0,
    scrollLeft: 0,
    page: 1,
    nextPage: true,
    timelines: [],
    currentTimeline: 0,
    products: {}
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    console.log("onload");
    //console.log(options.query);
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    console.log('quick index on ready');
    
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    console.log("quick/index-onshow");
    console.log(app.globalData.timelineTab);
    if (this.data.currentTab != getApp().globalData.timelineTab && getApp().globalData.timelineTab>0)
    {
      console.log('tab changed');
      this.setData({
        currentTab: app.globalData.timelineTab,
        page:1,
        nextPage:true
      });
      this.loadPage();
    }
    console.log('onshow currentTab'+this.data.currentTab);
    this.loadTimeline();    

    console.log("on show currentTab:" + this.data.currentTab);
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    console.log("onPullDownRefresh");
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    console.log("onReachBottom");
    this.setData({page: this.data.page+1});
    this.loadPage();
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
  loadPage: function () {
    console.log("loadPage");
    var self = this;
    
    //已经有数据
    if(!self.data.nextPage)
    {
      console.log("已经是最后一页");
      return;
    }

    console.log(self.data.products);
    console.log("before setdata");

    app.httpGet('/index.php?r=v1/product/index&timeline=' + self.data.currentTab + '&page='+self.data.page,{
      success: function(res){
        console.log(res);
        if(res.data.page<res.data.total_page)
        {
          self.setData({ nextPage: true });
        }
        else
        {
          self.setData({ nextPage: false });
        }
        //第一页直接覆盖
        if(self.data.page == 1)
        {
          self.setData(
            { products: res.data }
          )
        }
        else
        {
          var oldProducts = self.data.products;
          oldProducts.page = res.data.page;
          oldProducts.total = res.data.total;
          oldProducts.total_page = res.data.total_page;
          oldProducts.items = oldProducts.items.concat(res.data.items);
          self.setData(
            { products: oldProducts }
          )
        }
        console.log(self.data.products);
      }
    });
  },
  loadTimeline: function () {
    var self = this;
    app.httpGet('/index.php?r=v1/timeline/index', {
      success: function (res) {
        console.log(res);
        self.setData({
          timelines: res.data.items,
          currentTimeline: res.data.current
        });
        self.scrollTab();
        console.log("loadTimeline currentTab"+self.data.currentTab);
        if(self.data.currentTab != 0)
        {
          self.setData({
            page: 1,
            nextPage: true
            });
          self.loadPage();
        }
        
        console.log(self.data.timelines);
      }
    });
  },
  scrollTab: function () {
    var data = this.data;
    console.log('scrollTab');
    console.log("currentTimeline:" + data.currentTimeline);
    if (data.currentTab == 0) {
      var total = data.timelines.length;
      if (data.currentTimeline > 0) {
        if (data.currentTimeline > (total - 5)) {
          var offset = (total - 5) * 75;
          this.setData({ scrollLeft: offset, currentTab: data.timelines[data.currentTimeline].id });
        }
        else {
          var offset = (data.currentTimeline) * 75;
          console.log("offset:" + offset);
          this.setData({ scrollLeft: offset, currentTab: data.timelines[data.currentTimeline].id });
        }
      }
      console.log("currentTab:" + data.timelines[data.currentTimeline].id);
    }
  },
  swichNav: function (e) {
    console.log(e);
    console.log(e.currentTarget.dataset.id);
    this.setData({ 
      currentTab: e.currentTarget.dataset.id,
      page:1,
      nextPage:true
      });

    this.loadPage();
  },
  updateProductItem: function(product){
    var oldProducts = this.data.products;
  },
  getProductItem: function(id){
    var oldProducts = this.data.products;
    if(oldProducts.items)
    {
      for(var i=0;i<oldProducts.items.length;i++)
      {
        var item = oldProducts.items[i];
        if(item.id==id)
        {
          return item;
        } 
      }
    }
    return null;
  },
  updateProducts: function(){
    this.setData({
      products:this.data.products
    });
  },
  onItemClicked: function(e){
    console.log(e);
    wx.navigateTo({
      url: '/pages/product/view?id='+e.currentTarget.dataset.id,
    })
  },
  onLoveClicked: function (e) {
    var productId = e.currentTarget.dataset.id;
    var item = this.getProductItem(productId);
    var self = this;

    if (item.is_favorite == true) {
      app.httpDelete('/index.php?r=v1/favorite/index&id=' + productId, {
        success: function (res) {
          console.log(res);
          item.is_favorite = res.data.is_favorite;
          self.updateProducts();
          wx.showToast({
            title: '已取消',
            icon: 'none'
          });
        },
      });
    }
    else {
      app.httpPost('/index.php?r=v1/favorite/index', {
        success: function (res) {
          console.log(res);
          item.is_favorite = res.data.is_favorite;
          self.updateProducts();
          wx.showToast({
            title: '已关注',
          });
        },
      },
        { product_id: productId }
      );
    }
  },
  onBidClicked: function (e) {
    var productId = e.currentTarget.dataset.id;
    var item = this.getProductItem(productId);
    var self = this;

    if (item.next_bid >= item.price) {
      self.onBuyClicked(e);
      return;
    }

    if (item.can_bid) {
      wx.showModal({
        title: '确认要出价吗？',
        confirmText: '出价',
        content: item.next_bid + '',
        success: function (res) {
          if (res.confirm) {
            console.log('bid');
            app.httpPost('/index.php?r=v1/bid/index', {
              success: function (res) {
                console.log(res);
                if (res.code == 200) {
                  item.bid_total = res.data.bid_total;
                  item.next_bid = res.data.next_bid;
                  self.updateProducts();
                }
                else if (res.code == 100800) {
                  wx.showModal({
                    title: '出价错误',
                    content: '你需要缴纳保证金后才能参与拍卖,请先缴纳保证金',
                    confirmText: '缴纳保证金',
                    success: function (res) {
                      if (res.confirm) {
                        wx.navigateTo({
                          url: '/pages/my/paydeposit',
                        });
                      }
                    }
                  })
                }
                else {
                  wx.showToast({
                    title: res.msg,
                  })
                }
              }
            }, {
                product_id: item.id,
                price: item.next_bid
              });
          }
        }
      })
    }
    else {
      wx.showToast({
        title: '尚未开售',
        icon: 'none'
      })
    }
  },
  onBuyClicked: function (e) {
    var productId = e.currentTarget.dataset.id;
    var item = this.getProductItem(productId);
    var self = this;

    if (item.can_bid) {
      wx.showModal({
        title: '确认要出价吗？',
        confirmText: '出价',
        content: item.price + '',
        success: function (res) {
          if (res.confirm) {
            console.log('bid');
            app.httpPost('/index.php?r=v1/bid/buy', {
              success: function (res) {
                console.log(res);
                if (res.code == 200) {
                  item.bid_total = res.data.bid_total;
                  item.next_bid = res.data.next_bid;
                  self.updateProducts();
                  if (res.data.order_id) {
                    var url = "/pages/my/confirm?id=" + res.data.order_id;
                    wx.navigateTo({
                      url: url,
                    })
                  }
                }
                else if (res.code == 100800) {
                  wx.showModal({
                    title: '出价错误',
                    content: '你需要缴纳保证金后才能参与拍卖,请先缴纳保证金',
                    confirmText: '缴纳保证金',
                    success: function (res) {
                      if (res.confirm) {
                        action.payDeposit(self);
                      }
                    }
                  })
                }
                else {
                  wx.showToast({
                    title: res.msg,
                  })
                }
              }
            }, {
                product_id: item.id,
                price: item.next_bid
              });
          }
        }
      })
    }
    else {
      wx.showToast({
        title: '尚未开始',
        icon: 'none'
      })
    }

  },
})